package com.netmarch.common;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;


/**
 * @date 2016年12月29日下午9:26:24
 * 拦截空SESSION
 */
public class SystemInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = Logger.getLogger(SystemInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		
		String requestUrl = request.getRequestURI();
		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}else if (handler instanceof HandlerMethod) {
			HandlerMethod handlermethod = (HandlerMethod) handler;
			Login methodLogin = handlermethod.getMethodAnnotation(Login.class);
			Login classLogin = handlermethod.getBeanType().getAnnotation(Login.class);
			// 没有声明权限,放行
			if (null == methodLogin && null == classLogin) {
				return true;
			}
//			User user = (User) request.getSession().getAttribute("USER");
//			if (user == null) {
//				String url = request.getContextPath()+"/login";
//		        PrintWriter out = response.getWriter();
//		        out.println("<html>");   
//		        out.println("<script>");  
//		        out.println("window.open ('"+url+"','_parent')"); //作为父窗口打开  
//		        out.println("</script>");   
//		        out.println("</html>");       
//		        return false;
//			}

		} else {
			logger.warn("Unknow:" + requestUrl);
		}
		return true;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
	}
}
